package com.ecnu.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ecnu.common.annotation.Log;
import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.enums.BusinessType;
import com.ecnu.common.exception.ServiceException;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.ProjectReview;
import com.ecnu.system.domain.ProjectUser;
import com.ecnu.system.domain.dto.*;
import com.ecnu.system.domain.vo.ProjectViewVO;
import com.ecnu.system.service.IProjectJoinService;
import com.ecnu.system.service.IProjectReviewService;
import com.ecnu.system.service.IProjectService;
import com.ecnu.system.service.IProjectUserService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "活动审核管理")
@RestController
@RequestMapping("/project/join")
public class ProjectJoinController extends BaseController {

    @Autowired
    private IProjectJoinService joinService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IProjectUserService projectUserService;
    @Autowired
    private IProjectReviewService reviewService;

    /**
     * 活动人员报名管理
     */
//    @PreAuthorize("@ss.hasPermi('project:join:add')")
    @Log(title = "活动报名--新增", businessType = BusinessType.INSERT)
    @ApiOperation(value = "1、活动报名--新增")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody ProjectUser user)//加个字段是报名还是参与
    {
        //判断活动是否纯在，判断是否是报名时间之后，是的话不能报名
        Project project = projectService.getOne(new QueryWrapper<Project>().eq("id", user.getProId()));
        if (project == null) {
            return error("活动不存在");
        }
        if (project.getRegistrationType().equals("1")) {
            Date date = new Date();
            if (!date.after(project.getRegistrationStartTime()) || !date.before(project.getRegistrationEndTime())) {
                return error("当前时间不在活动报名时间内");
            }

        }
        if(project.getRegistrationType().equals("0")){
            user.setStatus("0");
        }
        else {
            user.setStatus("1");
        }
        //
        LoginUser loginUser = getLoginUser();//获取当前登录用户信息
        user.setUserId(loginUser.getUserId().toString());
        user.setUserName(loginUser.getUser().getNickName());
        return toAjax(joinService.insertProjectUser(user));
    }

    //    @PreAuthorize("@ss.hasPermi('project:join:list')")

    /**
     * 查询活动列表(有变动）
     */
    @GetMapping("/list")
    public AjaxResult list(@PathVariable String status) {
        return success(joinService.selectUnauditUser(status));
    }


    @Log(title = "活动报名--明细", businessType = BusinessType.OTHER)
    @ApiOperation(value = "1、活动报名--明细")
    @GetMapping("/proUserInfo")
    public AjaxResult ProUserInfo(@RequestParam("id") String id) {
        return joinService.selectProUserInfo(id);
    }

    @Log(title = "活动报名--审核", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "1、活动报名--审核")
    @PostMapping("/update")
    public AjaxResult update(@Valid @RequestBody ProjectUserFalseDTO dto) {
        LoginUser loginUser = getLoginUser();
        return toAjax(joinService.updateJoinStatus(dto,loginUser));
    }




    /***
     * 活动可见范围管理
     * @param proId
     * @return
     */
    @Log(title = "活动可见范围提交", businessType = BusinessType.INSERT)
    @ApiOperation(value = "2、活动可见范围提交")
    @PostMapping("/proVisible")
    public AjaxResult proVisible(@Valid @RequestBody ProVisibleDTO dto) {
        Project project = projectService.getOne(new QueryWrapper<Project>().eq("id", dto.getProId()));
        if (project == null) {
            return error("活动不存在");
        }
        LoginUser loginUser = getLoginUser();//获取当前登录用户信息

        return reviewService.saveByProId(project,loginUser);
    }

    @Log(title = "活动可见范围审核", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "2、活动可见范围审核")
    @PostMapping("/proReview")
    public AjaxResult proReview(@Valid @RequestBody ProReviewDTO dto) {
        Project project = projectService.getOne(new QueryWrapper<Project>().eq("id", dto.getProId()));
        if (project == null) {
            return error("活动不存在");
        }
        LoginUser loginUser = getLoginUser();//获取当前登录用户信息
        ProjectReview byId = reviewService.getById(dto.getId());
        if (byId == null) {
            return error("审核信息不存在");
        }
        if(!byId.getReviewStatus().equals("0")){
//            return success("活动已审核");
            throw new ServiceException("活动已审核，无法再次提交", HttpStatus.ACCEPTED);
        }
        boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
            .noneMatch(role -> role.getRoleId().equals(1L) || role.getRoleId().equals(2L)||  role.getRoleId().equals(103L));
        if (isUnauthorizedRole) {
            logger.error(loginUser.getUser().getNickName()+ "  该用户权限为："+loginUser.getUser().getRoles().get(0).getRoleName()+"，权限不足，无法审核");
            return error("权限不足，无法审核");
        }
        return reviewService.updateByProId(dto,project,loginUser);
    }

    @ApiOperation(value = "2、范围审核列表")
    @PostMapping("/selectList")
    public TableDataInfo selectList(@RequestBody  ProjectViewDTO pageDomain) {

        LoginUser loginUser = getLoginUser();//获取当前登录用户信息
        //审核列表
        List<ProjectViewVO> projectViewVOS = reviewService.selectList(loginUser, pageDomain.getName());
        //报名列表
        List<ProjectViewVO> projectUserVOS = projectUserService.getReviewList(loginUser, pageDomain.getName());
        projectViewVOS.addAll(projectUserVOS);
        projectViewVOS=projectViewVOS.stream()
                .sorted(Comparator.comparing(ProjectViewVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
                .collect(Collectors.toList());
        List<ProjectViewVO> projectViewVOS1 = OtherUtil.memoryPage(projectViewVOS, pageDomain.getPageDomain().getPageSize(), pageDomain.getPageDomain().getPageNum());
        return OtherUtil.tableSuccess2(projectViewVOS1,new PageInfo(projectViewVOS).getTotal() );
    }

    @Log(title = "范围审核--明细", businessType = BusinessType.OTHER)
    @ApiOperation(value = "2、范围审核--明细")
    @GetMapping("/proReviewInfo")
    public AjaxResult proReviewInfo(@RequestParam("id") String id) {
        return reviewService.selectReviewInfo(id,null);
    }
    @Log(title = "范围审核--明细", businessType = BusinessType.OTHER)
    @ApiOperation(value = "2、范围审核--明细")
    @GetMapping("/proInfo")
    public AjaxResult proInfo(@RequestParam("id") String id) {
        return reviewService.selectInfo(id);
    }

    /**
     * 我的提交
     */
    @ApiOperation(value = "3、我的提交")
    @PostMapping("/mySubmission")
    public TableDataInfo mySubmission(@RequestBody  ProjectViewDTO pageDomain) {
        LoginUser loginUser = getLoginUser();
        //审核列表
        List<ProjectViewVO> projectViewVOS = reviewService.mySubmissionList(loginUser, pageDomain.getName());
        //报名列表
        List<ProjectViewVO> projectUserVOS = projectUserService.mySubmissionList(loginUser, pageDomain.getName());
        projectViewVOS.addAll(projectUserVOS);
        projectViewVOS=projectViewVOS.stream()
                .sorted(Comparator.comparing(ProjectViewVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
                .collect(Collectors.toList());
        List<ProjectViewVO> projectViewVOS1 = OtherUtil.memoryPage(projectViewVOS, pageDomain.getPageDomain().getPageSize(), pageDomain.getPageDomain().getPageNum());
        return OtherUtil.tableSuccess2(projectViewVOS1,new PageInfo(projectViewVOS).getTotal() );
    }


    /****
     *
     * @param proId
     * @return
     */
    @Log(title = "活动报名状态", businessType = BusinessType.OTHER)
    @GetMapping("/proStatus")
    public AjaxResult proStatus(@PathVariable String proId) {
        LoginUser loginUser = getLoginUser();//获取当前登录用户信息
        return success(joinService.selectProJoinStatus(loginUser.getUserId().toString(), proId));
    }

    @Log(title = "根据活动查看报名人员", businessType = BusinessType.OTHER)
    @PostMapping("/proUserList")
    public TableDataInfo proUserById(@Valid @RequestBody ProjectUserDTO projectUserDTO) {
        LoginUser loginUser = getLoginUser();//获取当前登录用户信息
        return joinService.selectProUserById(projectUserDTO);
    }
}
